Subscribe to Windows IT Pro

What does PowerShell's [CmdletBinding()] Do?

It's a Great Trick, and a Big Part of "Script Cmdlets"
Posted @ 2/8/2012 12:18 PM By Don Jones

 

It's not unusual to see folks write PowerShell scripts and functions whose first line is [CmdletBinding()]. What's it do?

It's generally a big part of advanced functions, or what some folks call "script cmdlets." Basically, it turns on cmdlet-style parameter binding capabilities, either for a script or for a function. You really get four magical capabilities with it:

  • The ability to add [Parameter()] decorators to parameters - see "about_functions_advanced_parameters" in PowerShell for more detail. Technically, these can be used without adding [CmdletBinding()], but you almost always see them together.
  • The ability to use Write-Verbose and Write-Debug in your script or function, and have their output controlled by -Verbose and -Debug parameters of that script or function. You don't need to declare those parameters - [CmdletBinding()] adds them.
  • Your script or function picks up the other common parameters, too, like -EV and -EA (see "about_common_parameters")
  • The ability to have -whatif and -confirm added to your script or function, by specifying something like [CmdletBinding(SupportsShouldProcess=$True,ConfirmImpact=Medium)]. You still have to implement support for these switches by using $pscmdlet.ShouldProcess() in your script.

Related Content:

Comments

Add A Comment
    There are no comments to display. Be the first one!
You must log on before posting a comment.

Are you a new visitor? Register Here

Windows is a trademark of the Microsoft group of companies. Windows IT Pro is used by Penton Media Inc. under license from owner.